package com.qingke.pms.command.user;

import com.qingke.pms.command.UserCommand;
import com.qingke.pms.pojo.Project;
import com.qingke.pms.pojo.User;
import com.qingke.pms.util.PMSConsole;

public class AlterProjectCommand extends UserCommand {

	public AlterProjectCommand(User user) {
		super(user);
	}

	@Override
	public void execute() {
		Project project=null;
		while(true){
			String str=PMSConsole.promptNotEmpty("choose select project by id or code (id,code):");
			if("id".equalsIgnoreCase(str))
				project=byId();
			else if("code".equalsIgnoreCase(str))
				project=byCode();
			else{
				PMSConsole.println("err input");
				continue;
			}
			if(project==null)
				return ;
			break;
		}
		while(true){
			PMSConsole.println("alter (1.code 2.name 3.construction unit 4.first party) 5.confirm alter ");
			String str=PMSConsole.promptNotEmpty("alter project>");
			if("1".equalsIgnoreCase(str))
				code(project);
			else if("2".equalsIgnoreCase(str))
				name(project);
			else if("3".equalsIgnoreCase(str))
				constructionUnit(project);
			else if("4".equalsIgnoreCase(str))
				firstParty(project);
			else if("5".equalsIgnoreCase(str))
				break;
			else 
				PMSConsole.println("err input");
		}
		
		boolean isSuccess=dao.updateProject(project);
		if(isSuccess)
			PMSConsole.println("update project success.");
		else
			PMSConsole.println("update project failed.");
	}
	
	private Project byId(){
		int id=PMSConsole.getInt("project id:");
		if(!dao.isProjectExistById(id)){
			PMSConsole.println("the project is not existed.");
			return null;
		}
		return dao.selectProjectById(id);
	}
	
	private Project byCode(){
		String code=PMSConsole.promptNotEmpty("project code:");
		if(!dao.isProjectExistByCode(code)){
			PMSConsole.println("the project is not existed.");
			return null;
		}
		return dao.selectProjectByCode(code);
	}
	
	private void code(Project project){
		String code=PMSConsole.promptNotEmpty("project code:");
		if(dao.isProjectExistByCode(code)){
			PMSConsole.println("the project code have been existed.");
			return ;
		}
		project.setCode(code);
	}
	
	private void name(Project project){
		String name=PMSConsole.promptNotEmpty("project name:");
		project.setName(name);
	}
	
	private void constructionUnit(Project project){
		int id=PMSConsole.getInt("project construction unit id:");
		if(!dao.isCompanyExistById(id)){
			PMSConsole.println("the company is not existed.");
			return ;
		}
		if(id==project.getConstructionUnit()){
			PMSConsole.println("it is same construction unit.");
			return ;
		}
		project.setConstructionUnit(id);
	}
	
	private void firstParty(Project project){
		int id=PMSConsole.getInt("project first party id:");
		if(!dao.isCompanyExistById(id)){
			PMSConsole.println("the company is not existed.");
			return ;
		}
		if(id==project.getFirstParty()){
			PMSConsole.println("it is same first party unit.");
			return ;
		}
		project.setFirstParty(id);
	}

}
